<template>
  <div class="_editor">
    <div style="border: 1px solid #ccc">
      <Toolbar
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
        style="border-bottom: 1px solid #ccc"
      />
      <Editor
        :defaultConfig="editorConfig"
        :mode="mode"
        v-model="valueHtml"
        :style="'height: ' + props.height + 'px; overflow-y: hidden'"
        @onCreated="handleCreated"
      />
    </div>
  </div>
</template>
<script lang="ts" setup>
  import '@wangeditor/editor/dist/css/style.css'; // 引入 css
  import { onBeforeUnmount, shallowRef, computed } from 'vue';
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
  import { useGlobSetting } from '@/hooks/setting';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  const globSetting = useGlobSetting();
  const userStore = useUserStoreWidthOut();
  const token = userStore.getToken;
  const { uploadUrl } = globSetting;
  interface Props {
    modelValue: string;
    height?: number | string; // 编辑器的高度
  }
  interface EmitEvent {
    (e: 'update:modelValue', params: string): void;
  }
  const props = withDefaults(defineProps<Props>(), {
    height: 300,
  });
  const emit = defineEmits<EmitEvent>();
  const valueHtml = computed({
    get() {
      return props.modelValue;
    },
    set(value: string) {
      emit('update:modelValue', value);
    },
  });
  // 编辑器实例，必须用 shallowRef
  const editorRef = shallowRef();

  const mode = 'default'; // 模式：default、simple
  const toolbarConfig = {
    excludeKeys: ['fullScreen', 'group-video'],
  };
  const editorConfig = {
    height: 1000,
    placeholder: '请输入内容...',
    withCredentials: true, // 允许跨域携带 cookie
    MENU_CONF: {
      uploadImage: {
        server: uploadUrl,
        timeout: 20 * 1000, // 5s
        fieldName: 'file',
        meta: { scene: 'editor' },
        allowedFileTypes: ['image/*'],
        //metaWithUrl: true, // join params to url
        headers: {
          'Access-Control-Allow-Origin': 'origin',
          Authorization: `Bearer ${token}`,
        },
        maxFileSize: 2 * 1024 * 1024, // 2M

        base64LimitSize: 5 * 1024, // insert base64 format, if file's size less than 5kb
        // 自定义插入图片
        customInsert(res: any, insertFn) {
          // TS 语法
          // customInsert(res, insertFn) {                  // JS 语法
          // res 即服务端的返回结果

          // 从 res 中找到 url alt href ，然后插入图片
          insertFn(res.result.url, res.result.fileName, null);
        },
        onBeforeUpload(file) {
          console.log('onBeforeUpload', file);

          return file; // will upload this file
          // return false // prevent upload
        },
        onProgress(progress) {
          console.log('onProgress', progress);
        },
        onSuccess(file, res) {
          console.log('onSuccess', file, res);
        },
        onFailed(file, res) {
          alert(res.message);
          console.log('onFailed', file, res);
        },
        onError(file, err, res) {
          alert(err.message);
          console.error('onError', file, err, res);
        },
      },
    },
  };
  // 组件销毁时，也及时销毁编辑器
  onBeforeUnmount(() => {
    const { value } = editorRef;
    if (value === null) return;
    value.destroy();
  });
  const handleCreated = (editor: any) => {
    editorRef.value = editor; // 记录 editor 实例
    //console.log(editor.getConfig());
  };
</script>
<style lang="less">
  ._editor {
    // h1,
    // h2,
    // h3,
    // h4,
    // h5,
    // h6 {
    //   font-weight: bold;
    // }
    h1 {
      font-size: 2em;
    }
    h2 {
      font-size: 1.5em;
    }
    h3 {
      font-size: 1.17em;
    }
    h4 {
      font-size: 1em;
    }
    h5 {
      font-size: 0.83em;
    }
    h6 {
      font-size: 0.67em;
    }
  }
</style>
